import { USER_INFO, LOGIN_INFO, TENANTID } from './../mutation-types';
import { defineStore } from 'pinia';
import { createStorage } from '@/utils/Storage';
import { selectTenant } from '@/services/userService/lcdpLogin';

import { store } from '@/store';

const Storage = createStorage({ storage: localStorage });

export interface IUserState {
  loginInfo?: API.Login.LoginResult;
  userInfo?: API.Login.UserInfo;
  tenantId: string;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    loginInfo: Storage.get(LOGIN_INFO, {}),
    userInfo: Storage.get(USER_INFO, {}),
    tenantId: Storage.get(TENANTID, ''),
  }),
  getters: {
    getTenantId(): string {
      return this.tenantId;
    },
  },
  actions: {
    setUserInfo(userInfo: API.Login.UserInfo) {
      Storage.set(USER_INFO, userInfo);
      this.userInfo = userInfo;
    },
    setLoginInfo(loginInfo: API.Login.LoginResult) {
      Storage.set(LOGIN_INFO, loginInfo);
      this.loginInfo = loginInfo;
    },
    setTenantId(value: string) {
      Storage.set(TENANTID, value);
      this.tenantId = value;
    },
    async getUserInfo(callback = () => {}, tenantId?: string) {
      const newTenantId = tenantId ?? this.tenantId;
      const res = await selectTenant(newTenantId);
      this.userInfo = res;
      this.tenantId = newTenantId;
      callback();
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
  return useUserStore(store);
}
